'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = updateMany;

var _helpers = require('./helpers');

var _toMongoDottedObject = require('../utils/toMongoDottedObject');

var _toMongoDottedObject2 = _interopRequireDefault(_toMongoDottedObject);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable no-param-reassign */

function updateMany(model, tc, opts) {
  if (!model || !model.modelName || !model.schema) {
    throw new Error('First arg for Resolver updateMany() should be instance of Mongoose Model.');
  }
  if (!tc || tc.constructor.name !== 'TypeComposer') {
    throw new Error('Second arg for Resolver updateMany() should be instance of TypeComposer.');
  }

  const outputTypeName = `UpdateMany${tc.getTypeName()}Payload`;
  const outputType = tc.constructor.schemaComposer.getOrCreateTC(outputTypeName, t => {
    t.addFields({
      numAffected: {
        type: 'Int',
        description: 'Affected documents number'
      }
    });
  });

  const resolver = new tc.constructor.schemaComposer.Resolver({
    name: 'updateMany',
    kind: 'mutation',
    description: 'Update many documents without returning them: ' + 'Use Query.update mongoose method. ' + 'Do not apply mongoose defaults, setters, hooks and validation. ',
    type: outputType,
    args: (0, _extends3.default)({}, (0, _helpers.recordHelperArgs)(tc, (0, _extends3.default)({
      recordTypeName: `UpdateMany${tc.getTypeName()}Input`,
      removeFields: ['id', '_id'],
      isRequired: true
    }, opts && opts.record)), (0, _helpers.filterHelperArgs)(tc, model, (0, _extends3.default)({
      filterTypeName: `FilterUpdateMany${tc.getTypeName()}Input`,
      model
    }, opts && opts.filter)), (0, _helpers.sortHelperArgs)(tc, model, (0, _extends3.default)({
      sortTypeName: `SortUpdateMany${tc.getTypeName()}Input`
    }, opts && opts.sort)), (0, _helpers.skipHelperArgs)(), (0, _helpers.limitHelperArgs)((0, _extends3.default)({}, opts && opts.limit))),
    resolve: (() => {
      var _ref = (0, _asyncToGenerator3.default)(function* (resolveParams) {
        const recordData = resolveParams.args && resolveParams.args.record || {};

        if (!(typeof recordData === 'object') || Object.keys(recordData).length === 0) {
          return Promise.reject(new Error(`${tc.getTypeName()}.updateMany resolver requires ` + 'at least one value in args.record'));
        }

        resolveParams.query = model.find();
        (0, _helpers.filterHelper)(resolveParams);
        (0, _helpers.skipHelper)(resolveParams);
        (0, _helpers.sortHelper)(resolveParams);
        (0, _helpers.limitHelper)(resolveParams);

        resolveParams.query = resolveParams.query.setOptions({ multi: true }); // eslint-disable-line
        resolveParams.query.update({ $set: (0, _toMongoDottedObject2.default)(recordData) });

        let res;

        // `beforeQuery` is experemental feature, if you want to use it
        // please open an issue with your use case, cause I suppose that
        // this option is excessive

        if (resolveParams.beforeQuery) {
          res = yield resolveParams.beforeQuery(resolveParams.query, resolveParams);
        } else {
          res = yield resolveParams.query.exec();
        }

        if (res.ok) {
          return {
            numAffected: res.n || res.nModified
          };
        }

        // unexpected response
        throw new Error(JSON.stringify(res));
      });

      return function resolve(_x) {
        return _ref.apply(this, arguments);
      };
    })()
  });

  return resolver;
}